import React, { useState, useRef } from 'react';
import { User } from '../types';

interface AvatarProps {
  user: User;
  size?: 'sm' | 'md' | 'lg' | 'xl';
  editable?: boolean;
  onAvatarChange?: (file: File) => void;
  className?: string;
}

const Avatar: React.FC<AvatarProps> = ({ 
  user, 
  size = 'md', 
  editable = false, 
  onAvatarChange,
  className = ''
}) => {
  const [isHovered, setIsHovered] = useState(false);
  const [imageError, setImageError] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const sizeClasses = {
    sm: 'w-8 h-8',
    md: 'w-12 h-12',
    lg: 'w-16 h-16',
    xl: 'w-20 h-20'
  };

  const textSizes = {
    sm: 'text-sm',
    md: 'text-lg',
    lg: 'text-xl',
    xl: 'text-2xl'
  };

  const handleAvatarClick = () => {
    if (editable && fileInputRef.current) {
      fileInputRef.current.click();
    }
  };

  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file && onAvatarChange) {
      // 验证文件类型
      if (!file.type.startsWith('image/')) {
        alert('请选择图片文件');
        return;
      }
      
      // 验证文件大小（最大2MB）
      if (file.size > 2 * 1024 * 1024) {
        alert('图片大小不能超过2MB');
        return;
      }

      onAvatarChange(file);
    }
  };

  const handleImageError = () => {
    setImageError(true);
  };

  const getInitials = (username: string) => {
    return username.charAt(0).toUpperCase();
  };

  // 检查是否有有效的头像URL
  const hasValidAvatar = user.avatar && !imageError && 
    (user.avatar.startsWith('http') || user.avatar.startsWith('/'));

  return (
    <div className={`relative ${className}`}>
      <div
        className={`${sizeClasses[size]} rounded-full bg-gray-200 flex items-center justify-center cursor-pointer transition-all duration-200 ${
          editable ? 'hover:opacity-80' : ''
        } ${isHovered && editable ? 'ring-2 ring-primary-500' : ''}`}
        onClick={handleAvatarClick}
        onMouseEnter={() => setIsHovered(true)}
        onMouseLeave={() => setIsHovered(false)}
      >
        {hasValidAvatar ? (
          <img
            src={user.avatar}
            alt={`${user.username}的头像`}
            className={`${sizeClasses[size]} rounded-full object-cover`}
            onError={handleImageError}
            onLoad={() => setImageError(false)}
          />
        ) : (
          <span className={`${textSizes[size]} text-gray-600 font-semibold`}>
            {getInitials(user.username)}
          </span>
        )}
      </div>

      {editable && (
        <>
          <input
            ref={fileInputRef}
            type="file"
            accept="image/*"
            onChange={handleFileChange}
            className="hidden"
          />
          {isHovered && (
            <div className="absolute inset-0 flex items-center justify-center bg-black bg-opacity-50 rounded-full">
              <span className="text-white text-xs font-medium">更换头像</span>
            </div>
          )}
        </>
      )}
    </div>
  );
};

export default Avatar; 